﻿var Access = {
	adSchemaTables: 20,
	createDatabase: function(filename) {
		if (Local.fileExists(filename)) return;
		var catalog = new ActiveXObject("ADOX.Catalog");
		try {
			catalog.Create(Common.format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"${0}\"", [filename]));
			createDatabase = true;
			return true;
		} catch(ex) {
			alert(ex.message);
		} finally {
			catalog = null;
		}
	},
	execute: function(filename, sql) {
		if (!filename || !sql) return;
		if (!Local.fileExists(filename)) return;
		var connection = new ActiveXObject("ADODB.Connection");
		try {
			connection.Open(Common.format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"${0}\"", [filename]));
			connection.Execute(sql);
			connection.Close();
			return true;
		} catch(ex) {
			alert(ex.message);
		} finally {
			connection = null;
		}
	},
	tables: function(filename) {
		if (!filename) return;
		var result = {};
		var connection = new ActiveXObject("ADODB.Connection");
		try {
			connection.Open(Common.format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"${0}\"", [filename]));
			var recordset = connection.OpenSchema(adSchemaTables);
			var result = false;
			while (!recordset.EOF) {
				if (recordset("TABLE_TYPE") == "TABLE")
					result[recordset("TABLE_NAME")] = true;
				recordset.MoveNext();
			}
			recordset.Close();
			connection.Close();
			return result;
		} catch(ex) {
			alert(ex.message);
		} finally {
			recordset = null;
			connection = null;
		}
	},
	query: function(filename, sql, func) {
		if (!filename || !sql || !func) return;
		var connection = new ActiveXObject("ADODB.Connection");
		try {
			connection.Open(Common.format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"${0}\"", [filename]));
			var recordset = new ActiveXObject("ADODB.Recordset");
			recordset.Open(sql, connection);
			while (!recordset.EOF) {
				if (func(recordset)) break;
				recordset.MoveNext();
			}
			recordset.Close();
			connection.Close();
			return true;
		} catch(ex) {
			alert(ex.message);
		} finally {
			recordset = null;
		}
	}
};